package com.danco.sn.model.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.danco.sn.apientities.FriendshipStatus;
import com.danco.sn.apientities.IFriend;
import com.danco.sn.apientities.IUser;

public class FriendDAO extends GenericDAO<IFriend> {

	private static final String STATUS = "status";
	private static final String FIRST_NAME = "firstName";
	private static final String LAST_NAME = "lastName";
	private static final String CURRENT_USER = "currentUser";
	private static final String FRIEND = "friend";

	public FriendDAO() {
		super(IFriend.class);
	}

	// list user's friend or query in friend
	@SuppressWarnings("unchecked")
	public List<IUser> getListFriend(Session session, IUser user,
			FriendshipStatus status) throws HibernateException {
		Criteria criteria = session.createCriteria(IFriend.class)
				.setProjection(Projections.property(FRIEND))
				.add(Restrictions.eq(CURRENT_USER, user))
				.add(Restrictions.eq(STATUS, status.toString()));
		List<IUser> friendList = criteria.list();
		return friendList;
	}

	// search people which in friend
	@SuppressWarnings("unchecked")
	public List<IUser> searchFriend(Session session, IUser user, String name,
			String lastName) throws HibernateException {
		Criteria criteria = session
				.createCriteria(IFriend.class)
				.setProjection(Projections.property(CURRENT_USER))
				.add(Restrictions.eq(STATUS,
						FriendshipStatus.APPROVE.toString()))
				.add(Restrictions.eq(FRIEND, user))
				.setFetchMode(CURRENT_USER, FetchMode.JOIN)
				.createCriteria(CURRENT_USER);

		if (name != null) {
			criteria.add(Restrictions.like(FIRST_NAME, name.trim()));
		}
		if (lastName != null) {
			criteria.add(Restrictions.like(LAST_NAME, lastName.trim()));
		}
		if (name == null && lastName == null) {
			return null;
		}

		List<IUser> userList = criteria.list();
		return userList;// Check collection on null
	}

}
